import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useCartStore = defineStore(
  'cart',
  () => {
    // 用户信息
    const cartList = ref([])

    // 添加到购物车
    const addToCart = goods => {
      const oldGoods = cartList.value.find(item => item.proid === goods.proid)
      if (oldGoods) {
        oldGoods.number += goods.number
      } else {
        cartList.value.push(goods)
      }
    }

    // 修改商品的选中状态
    const changeGoodsState = goods => {
      const oldGoods = cartList.value.find(item => item.proid === goods.proid)

      if (oldGoods) {
        oldGoods.state = goods.state
      }
    }

    // 修改商品的数量
    const changeGoodsNumber = goods => {
      const oldGoods = cartList.value.find(item => item.proid === goods.proid)

      if (oldGoods) {
        oldGoods.number = goods.number
      }
    }

    // 删除购物车商品
    const deleteGoods = proid => {
      cartList.value = cartList.value.filter(item => item.proid !== proid)
    }

    const isAllChecked = computed(() =>
      cartList.value.every(item => item.state)
    )

    // 获取购物车总数
    const getTotalCount = () => {
      return cartList.value.reduce((total, item) => total + item.number, 0)
    }

    // 获取选中商品的总金额
    const getTotalAmount = () => {
      return cartList.value
        .filter(item => item.state)
        .reduce((total, item) => total + item.number * item.price, 0)
    }

    // 全选 & 反选
    const selectAllOrNot = isSelect => {
      cartList.value.forEach(item => {
        item.state = isSelect
      })
    }

    return {
      cartList,
      getTotalCount,
      addToCart,
      changeGoodsState,
      changeGoodsNumber,
      deleteGoods,
      getTotalAmount,
      isAllChecked,
      selectAllOrNot
    }
  },
  { persist: true }
)
